import ButtonRegular from "@/components/composite/ButtonRegular/main"
import Checkbox from "@/components/form_item/Checkbox"
import CodeCountdownTimer from "@/components/form_item/CodeCountdownTimer"
import { ReactHookFormDatePicker } from "@/components/form_item/DatePicker"
import DateTimePicker from "@/components/form_item/DateTimePicker"
import InputCode from "@/components/form_item/InputCode"
import InputEmail from "@/components/form_item/InputEmail"
import InputName from "@/components/form_item/InputEnglishName"
import InputMoneyText from "@/components/form_item/InputMoneyText"
import InputPassword from "@/components/form_item/InputPassword"
import InputPhoneNumber from "@/components/form_item/InputPhoneNumber"
import InputText from "@/components/form_item/InputText"
import Radio from "@/components/form_item/Radio"
import Selection from "@/components/form_item/Selection"
import TextareaText from "@/components/form_item/TextareaText"
import { DataPickerType } from "@/components/form_item/formItemConfig"
import styled from "@emotion/styled"
import { FormEventHandler, HTMLAttributes, RefObject, useEffect } from "react"
import {
    Control,
    FieldValues,
    FormProvider,
    FormState,
    useForm,
    UseFormHandleSubmit,
} from "react-hook-form"

type Props = HTMLAttributes<HTMLDivElement> & {
    ref?: RefObject<unknown>
    queryList: (queryKeyType | DataPickerType)[]
    onSubmit: FormEventHandler<HTMLDivElement> &
    (() => Promise<void>) &
    _.DebouncedFuncLeading<(data: never) => Promise<void>>
    sendCode?: () => Promise<{ success: boolean }>
    back?: () => void
    showSubmitButton?: boolean
    excludingUIName?: object
    customOnClick?: () => void
}

type queryKeyType =
    | "submitButton"
    | "LoginCountdown"
    | "username"
    | "username1"
    | "phone"
    | "phoneNumber"
    | "phoneNumberPla"
    | "phoneNumberPalF"
    | "password"
    | "email"
    | "verify"
    | "checkbox"
    | "loginCheckbox"
    | "radio"
    | "select"
    | "otherKey"
    | "otherApiKey2"
    | "passwordSet"
    | "passwordExp"
    | "code"
    | "codeCountdown"
    | "emailNoPlaceholder"
    | "selectPage"
    | "datetime-page1"
    | "getCode"
    | "EnglishName"
    | "textareaText"
    | "deposit-inputMoneyText"
    | "deposit-inputMoneyText-custom"

const FormFieldItem = (props: {
    key: queryKeyType | DataPickerType
    control: Control
    reset: Props
    formState: FormState<FieldValues>
    handleSubmit: UseFormHandleSubmit<FieldValues>
}) => {
    const { key, control, reset, handleSubmit, formState } = props
    //fieldName 才是接口提交的参数key, queryKeyType 不等于 api的请求参数key
    //queryKeyType 可以随便自定义。用已区分不同API参数相同时UI不一致的情况
    //例如下面的password, api接口都是password, 但不同页面会显示不同的ui

    //这里的demo fieldName 需要根据实际情况自行修改。不同的case可以添加不同UI下的相同fieldName
    switch (key) {
        case "username": // queryKeyType === apiKey
            return (
                <InputText
                    key={key}
                    fieldName={"username"}
                    showPlaceholder={true}
                    placeholder={"User Name(5-30)"}
                />
            )
        case "username1": // queryKeyType === apiKey
            return (
                <InputText
                    key={key}
                    fieldName={"username1"}
                    showPlaceholder={false}
                    placeholder={"User Name(5-30)"}
                />
            )
        case "phone":
            return (
                <InputPhoneNumber
                    key={key}
                    fieldName={"phone"}
                    showPlaceholder={true}
                />
            )
        case "phoneNumber":
            return (
                <InputPhoneNumber
                    key={key}
                    fieldName={"phone1"}
                    showPlaceholder={false}
                    isPhoneType={false}
                />
            )
        case "phoneNumberPla":
            return (
                <InputPhoneNumber
                    key={key}
                    fieldName={"phone2"}
                    showPlaceholder={true}
                    placeholder={"显示placeholder"}
                    isPhoneType={false}
                />
            )
        case "phoneNumberPalF":
            return (
                <InputPhoneNumber
                    key={key}
                    fieldName={"phone3"}
                    showPlaceholder={false}
                />
            )
        case "password":
            return (
                <InputPassword
                    key={key}
                    fieldName={"password"}
                />
            )
        case "passwordExp":
            // queryKeyType !== apiKey
            // showPlaceholder: boolean //是否显示placeholder
            return (
                <InputPassword
                    key={key}
                    fieldName={"password"}
                    showPlaceholder={false}
                />
            )
        case "passwordSet": // queryKeyType !== apiKey
            return (
                <InputPassword
                    key={key}
                    fieldName={"password"}
                    showVerifyBox={true}
                />
            )
        case "email":
            return (
                <InputEmail
                    key={key}
                    fieldName={"email"}
                    showPlaceholder={true}
                />
            )
        case "emailNoPlaceholder":
            return (
                <InputEmail
                    key={key}
                    fieldName={"email_test"}
                    showPlaceholder={false}
                />
            )
        case "code": //邮箱验证码。短信验证码
            return (
                <InputCode
                    key={key}
                    fieldName={"code"}
                    control={control}
                    autoSubmit={true}
                    callBackSubmit={reset?.onSubmit}
                    ref={reset?.ref}
                />
            )
        case "checkbox":
            return (
                <Checkbox
                    key={key}
                    fieldName={"checkbox"}
                />
            )
        case "radio":
            return (
                <Radio
                    key={key}
                    fieldName={"radio"}
                />
            )
        case "loginCheckbox":
            return (
                <Agree key={key}>
                    <Checkbox fieldName={"checkbox"} />
                    <SpanA>I agree to the</SpanA>
                    <SpanB>Terms of use</SpanB>
                    <SpanA>and</SpanA>
                    <SpanB>Privacy policy.</SpanB>
                </Agree>
            )
        case "select":
            return (
                <Selection
                    key={key}
                    fieldName={"select"}
                />
            )
        case "otherKey":
            return (
                <InputText
                    key={key}
                    fieldName={"otherKey"}
                />
            )
        case "otherApiKey2":
            return (
                <InputText
                    key={key}
                    fieldName={"otherApiKey2"}
                />
            )
        case "codeCountdown":
            return (
                <CodeCountdownTimer
                    key={key}
                    // @ts-ignore
                    sendCode={reset?.sendCode}
                />
            )
        case "LoginCountdown":
            return (
                <VerifyBox key={key}>
                    <Tipbacklogin onClick={reset?.back}>Reset phone number</Tipbacklogin>
                    <CodeCountdownTimer
                        // @ts-ignore
                        sendCode={reset?.sendCode}
                    />
                </VerifyBox>
            )
        case "selectPage":
            // demo 自定义传入selectItems
            return (
                <DivContainer key={key}>
                    <Selection
                        key={key + "Selection"}
                        style={{ border: "1px solid blue" }}
                        onClick={handleSubmit(reset?.onSubmit)}
                        fieldName={"querySelectionKey1"}
                    />
                    <DatePickerContainer>
                        <ReactHookFormDatePicker
                            control={control}
                            fieldName={"data-time-test-API-KEY"}
                            onClick={handleSubmit(reset?.onSubmit)}
                        />
                    </DatePickerContainer>
                </DivContainer>
            )
        case "date":
            return (
                <DateTimePicker
                    key={key}
                    fieldName={"data-time1"}
                    inputType={"date"}
                />
            )
        case "time":
            return (
                <DateTimePicker
                    key={key}
                    fieldName={"data-time2"}
                    inputType={"time"}
                />
            )
        case "week":
            return (
                <DateTimePicker
                    key={key}
                    fieldName={"data-time3"}
                    inputType={"week"}
                />
            )
        case "month":
            return (
                <DateTimePicker
                    key={key}
                    fieldName={"data-time4"}
                    inputType={"month"}
                />
            )
        case "datetime-local":
            return (
                <DateTimePicker
                    key={key}
                    fieldName={"data-time5"}
                    inputType={"datetime-local"}
                />
            )
        case "submitButton":
            return (
                <SubmitButton
                    key={key}
                    onClick={handleSubmit(reset?.onSubmit)}
                    // @ts-ignore
                    variant={
                        formState.isValid
                            ? SubmitButtonVerifyOkBackgroundColor
                            : SubmitButtonBackgroundColor
                    }
                >
                    SubmitButton
                </SubmitButton>
            )
        case "getCode":
            return (
                <SubmitButton
                    key={key}
                    onClick={handleSubmit(reset?.onSubmit)}
                    // @ts-ignore
                    variant={
                        formState.isValid
                            ? SubmitButtonVerifyOkBackgroundColor
                            : SubmitButtonBackgroundColor
                    }
                >
                    Get code
                </SubmitButton>
            )
        case "EnglishName":
            return (
                <InputName
                    name={key}
                    key={key}
                    control={control}
                    fieldName="fullName"
                />
            )
        case "textareaText":
            return (
                <TextareaText
                    key={key}
                    fieldName="description"
                    maxLength={1000}
                    label="Feedback Content"
                    placeholder="Your suggestion matters. What can we improve on?"
                />
            )
        case "deposit-inputMoneyText":
            return (
                <InputMoneyText
                    key={key}
                    fieldName="depositMoneyText"
                    label="deposit"
                    placeholder="deposit?"
                />
            )
        case "deposit-inputMoneyText-custom":
            return (
                <InputMoneyText
                    key={key}
                    fieldName="depositMoneyCustom"
                    label="deposit"
                    placeholder="deposit?"
                    customText={"Withdrawal All"}
                    customOnClick={reset?.customOnClick}
                    // showClear={false}
                    // @ts-ignore
                    ref={reset?.ref}
                />
            )
        //后面还可以继续添加queryKeyType
        default:
            return null
    }
}

function ReactFormProvider(props: Props) {
    const {
        showSubmitButton = true,
        onSubmit,
        //不在UI中显示的api查询值放这里、例如：
        // {
        //   total: 100
        // }
        excludingUIName,
        queryList,
        ref,
        children,
    } = props
    const methods = useForm()
    const { control, reset, handleSubmit, formState } = methods
    useEffect(() => {
        if (excludingUIName && Object.keys(excludingUIName as object).length > 0) {
            reset(excludingUIName)
        }
    }, [reset])
    return (
        <FormProvider {...methods}>
            {queryList.map((list, idnex) => {
                return FormFieldItem({
                    key: list,
                    control: control,
                    reset: props,
                    formState,
                    handleSubmit,
                })
            })}
            {showSubmitButton && (
                <SubmitButton
                    onClick={handleSubmit(onSubmit)}
                    // @ts-ignore
                    variant={
                        formState.isValid
                            ? SubmitButtonVerifyOkBackgroundColor
                            : SubmitButtonBackgroundColor
                    }
                >
                    SubmitButton
                </SubmitButton>
            )}
        </FormProvider>
    )
}

export default ReactFormProvider

const SubmitButtonBackgroundColor = {
    type: "solid",
    backgroundColorLeft: "#FF99B3 1.52%",
    backgroundColorRight: "#FFC2EB 100%",
}

const SubmitButtonVerifyOkBackgroundColor = {
    type: "solid",
    backgroundColorLeft: "#FF3568 1.52%",
    backgroundColorRight: "#FF5CC9 100%",
}

const SubmitButton = styled(ButtonRegular)`
    height: 48rem;
    width: 100%;
    font-family: "Gilroy", sans-serif;
    font-weight: 500;
    font-size: 16rem;
    line-height: 24rem;
    letter-spacing: 0;
    text-align: center;
    outline: none;
    border: none;
    box-shadow: none;
    margin-top: 20rem;
`

const DatePickerContainer = styled.div`
    flex: 1;
    border: 1px solid #f2f3f5;
    border-radius: 8rem;
    background-color: #fff;
`

const DivContainer = styled.div`
    flex: 1;
    display: flex;
    flex-direction: row;
    gap: 10rem;
    margin-top: 35rem;
`

const Agree = styled.div`
    display: flex;
    justify-content: flex-start;
    align-items: center;
`

const SpanA = styled.span`
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 12rem;
    line-height: 16rem;
    letter-spacing: 0;
    color: #6a7081;
`

const SpanB = styled.span`
    font-family: "Gilroy", sans-serif;
    font-weight: 500;
    font-size: 12rem;
    line-height: 16rem;
    letter-spacing: 0;
    text-decoration: underline;
    text-decoration-style: solid;
    text-decoration-offset: 0;
    text-decoration-thickness: 0%;
    color: #ff356b;
    margin: 0 3rem;
`

const VerifyBox = styled.div`
    display: flex;
    justify-content: space-between;
    margin-top: 32rem;
`

const Tipbacklogin = styled.p`
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 12rem;
    line-height: 16rem;
    letter-spacing: 0;
    color: #fb2d60;
    margin: 0;
    padding: 0;
`
